﻿using System.Linq;
using System.Web.Mvc;
 using AppStore.Domain.Abstract;
 using AppStore.Domain.Entities;
using AppStore.Models;

namespace AppStore.Controllers
{
    public class CartController : Controller
    {
        private IApplicationRepository _applicationRepository;

        public CartController(IApplicationRepository applicationRepository)
        {
            _applicationRepository = applicationRepository;
        }

        public ViewResult Index(string returnUrl)
        {
            return View(new CartIndexViewModel {Cart = GetCart(), returnUrl = returnUrl});
        }

        [ChildActionOnly]
        public PartialViewResult CartLink()
        {
            return PartialView(GetCart());
        }


        public ActionResult AddToCart(int applicationId, string returnUrl)
        {
            Application app = _applicationRepository.Applications.FirstOrDefault(a => a.applicationId == applicationId);

            if (app != null)
            {
                GetCart().AddItem(app);
            }

            return Redirect(returnUrl);
            //return RedirectToAction("Browse", "Application", new { returnUrl });
        }
        [HttpPost]
        public ActionResult RemoveFromCart(int applicationId, string returnUrl)
        {
            Application app = _applicationRepository.Applications.FirstOrDefault(a => a.applicationId == applicationId);

            if (app != null)
            {
                GetCart().RemoveItem(app);
            }
            return Redirect(returnUrl);
            //return RedirectToAction("Browse", "Application",new { returnUrl });
        }

        private Cart GetCart()
        {
            Cart cart = (Cart) Session["Cart"];

            if (cart == null)
            {
                cart = new Cart();
                Session["Cart"] = cart;
            }
            return cart;
        }
    }
}
